package com.lintf.distributed.transaction.order.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lintf.distributed.transaction.DeductInventoryEvent;
import com.lintf.distributed.transaction.order.entity.Message;
import com.lintf.distributed.transaction.order.entity.Order;
import com.lintf.distributed.transaction.order.service.MessageService;
import com.lintf.distributed.transaction.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class MessageTimeoutTask {

    private final MessageService messageService;
    private final OrderService orderService;

    @Scheduled(fixedRate = 60000)
    public void checkTimeoutMessages() {
        // 查询状态=1（已发送）且超过30分钟未更新的消息
        List<Message> timeoutMessages = messageService.findMessageByTimeout(1,
                30 * 60 * 1000L
        );
        timeoutMessages.forEach(this::updateTimeOut);
    }

    private void updateTimeOut(Message message) {
        log.warn("消息处理超时: {}", message.getMessageId());

        // 更新消息状态为超时
        message.setStatus(4);
        messageService.updateById(message);
        DeductInventoryEvent deductInventoryEvent = JSONObject.parseObject(message.getContent(), DeductInventoryEvent.class);
        // 更新订单状态
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, deductInventoryEvent.getOrderId())
                .set(Order::getStatus, "TIMEOUT");
        orderService.update(updateWrapper);
    }
}